package com.xiaoy.core.remote.webservice.client.cxf;

import java.util.List;

import javax.xml.namespace.QName;
import javax.xml.ws.WebServiceException;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xiaoy.core.remote.webservice.client.KeyValue;
import com.xiaoy.core.remote.webservice.client.MyWebServerVO;
import com.xiaoy.core.remote.webservice.client.MyWebService;

@org.springframework.stereotype.Service("cxfImpl")
public class CXFImpl implements MyWebService {
	protected Logger	logger	= LoggerFactory.getLogger(getClass());
	@Override
	public String execution(MyWebServerVO vo) throws WebServiceException {
		
		
		String serverUrl = vo.getServerUrl();
		String namespace = vo.getNamespace();
		String method = vo.getMethod();
		List<KeyValue>kvs = vo.getParams();
		Object[] ps = new Object[kvs.size()];
		
		QName name=new QName("namespace", namespace);
		
		JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance(); 
		
		System.out.println("serverUrl-->"+serverUrl);
		System.out.println("namespace-->"+namespace);
		System.out.println("method-->"+method);
		
		Client client = dcf.createClient(serverUrl);
		for (int i=0;i<kvs.size();i++) {
			
			KeyValue kv = kvs.get(i);
			ps[i] = kv.getValue();
		}
		
		Object[] object;
		try {
			object = (Object[]) client.invoke(name,method,ps);
			
			if (object.length>1) {
				if (object[0]!=null) {
					return object[0].toString();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("没有读取到webserivce数据", e);
		}
		throw new WebServiceException("没有读取到webserivce数据");
	}

	public static void main(String[] args) throws WebServiceException {
		CXFImpl cxf = new CXFImpl();
		MyWebServerVO vo = new MyWebServerVO();
		vo.setServerUrl("http://192.168.0.23:7001/soa-infra/services/default/Project1/Vacate.service?WSDL");
		vo.setNamespace("http://xmlns.oracle.com/bpmn/bpmnProcess/Vacate");
		vo.setMethod("start");
		
		vo.addParam("day", "1");
		vo.addParam("managerUser", "test02");
		vo.addParam("humanUser", "test02");
		vo.addParam("bossUser", "test02");
		vo.addParam("reapplyUser", "test02");
		
		cxf.execution(vo);
	}
	
	
}
